package com.st.bottomnavigation.ui.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.st.bottomnavigation.R;
import com.st.bottomnavigation.bean.test.Student;
import com.st.bottomnavigation.service.TestService;
import com.st.bottomnavigation.ui.adapter.MyItemDecoration;
import com.st.bottomnavigation.ui.adapter.test.RecyclerViewAdapter;
import com.st.bottomnavigation.ui.zxing.CaptureActivity;
import com.st.bottomnavigation.ui.zxing.ZXingUtils;
import com.st.bottomnavigation.utils.Data;
import com.st.bottomnavigation.utils.DialogUtils;
import com.st.bottomnavigation.utils.RetrofitUtil;
import com.st.bottomnavigation.utils.SystemUtils;

import java.util.ArrayList;
import java.util.Locale;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 组件库案例
 */
public class GroupActivity extends BaseActivity {

    private Button alertTest;
    private Button dip_to_px;
    private Button getScreenValue;
    private Boolean isPaused = false;
    private int scrollX = 0;
    private TextView tv_marquee;
    private TextView tv_date;
    private RecyclerView recyclerView_student;
    private ListView ListView_student;

    private LinearLayout ll_spinner;
    private LinearLayout ll_dialog;
    private LinearLayout ll_text;
    private LinearLayout ll_RecyclerView;
    private LinearLayout ll_scan;
    private TestService testService;
    private RecyclerViewAdapter recyclerViewAdapter;
    protected static final int RESULT_SPEECH = 1;//语音识别请求码
    protected static final int RESULT_SCAN = 2;//扫描识别请求码
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private SpeechRecognizer speechRecognizer;
    private EditText editText;
    @Override
    protected int getContentViewId() {
        return R.layout.activity_group;
    }

    @Override
    protected String getHeaderTitle() {
        return "组件库案例";
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (speechRecognizer != null) {
            speechRecognizer.destroy();
            speechRecognizer = null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        editText = findViewById(R.id.editText);
        SpeechRecognizer.isRecognitionAvailable(this);
        // 初始化 SpeechRecognizer
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        // 设置监听器
        speechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {
                Toast.makeText(GroupActivity.this, "开始说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBeginningOfSpeech() {
                // 开始说话
            }

            @Override
            public void onRmsChanged(float rmsdB) {
                // 音量变化
            }

            @Override
            public void onBufferReceived(byte[] buffer) {
                // 接收语音数据
            }

            @Override
            public void onEndOfSpeech() {
                Toast.makeText(GroupActivity.this, "结束说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error) {
                String message;
                switch (error) {
                    case SpeechRecognizer.ERROR_AUDIO:
                        message = "音频错误";
                        break;
                    case SpeechRecognizer.ERROR_CLIENT:
                        message = "客户端错误";
                        break;
                    case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                        message = "权限不足";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK:
                        message = "网络错误";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                        message = "网络超时";
                        break;
                    case SpeechRecognizer.ERROR_NO_MATCH:
                        message = "没有匹配的识别结果";
                        break;
                    case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                        message = "识别服务繁忙";
                        break;
                    case SpeechRecognizer.ERROR_SERVER:
                        message = "服务器错误";
                        break;
                    case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                        message = "未检测到语音输入";
                        break;
                    default:
                        message = "未知错误";
                        break;
                }
                Toast.makeText(getApplicationContext(), "识别错误：" + message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResults(Bundle results) {
                // 获取最终识别结果
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (matches != null && !matches.isEmpty()) {
                    editText.setText(matches.get(0)); // 显示识别结果
                    editText.setSelection(editText.getText().length()); // 光标移动到最后
                }
            }

            @Override
            public void onPartialResults(Bundle partialResults) {
                // 获取部分识别结果
                ArrayList<String> partialMatches = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (partialMatches != null && !partialMatches.isEmpty()) {
                    editText.setText(partialMatches.get(0)); // 实时更新文本
                    editText.setSelection(editText.getText().length());
                }
            }

            @Override
            public void onEvent(int eventType, Bundle params) {
                // 其他事件
            }
        });
        // 检查并请求权限
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
//                    != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this,
//                        new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION);
//            } else {
//                startSpeechRecognition();
//            }
//        } else {
//            startSpeechRecognition();
//        }
        //初始化网络请求
        testService = RetrofitUtil.build(TestService.class);
        initView();
        listener();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startSpeechRecognition();
            } else {
                Toast.makeText(this, "录音权限被拒绝，无法进行语音识别", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void initView() {
        super.initView();
        ll_spinner = findViewById(R.id.ll_spinner);
        ll_spinner.setVisibility(View.GONE);
        ll_dialog = findViewById(R.id.ll_dialog);
        ll_dialog.setVisibility(View.GONE);
        ll_text = findViewById(R.id.ll_text);
        ll_text.setVisibility(View.GONE);
        ll_RecyclerView = findViewById(R.id.ll_RecyclerView);
        ll_RecyclerView.setVisibility(View.GONE);
        ll_scan = findViewById(R.id.ll_scan);
        ll_scan.setVisibility(View.GONE);

        //
        tv_marquee = findViewById(R.id.tv_marquee);
        tv_date = findViewById(R.id.tv_date);
        tv_marquee.setSelected(true);// 让跑马灯效果一开始就运行
        //
        recyclerView_student = findViewById(R.id.recyclerView_student);
        ListView_student = findViewById(R.id.ListView_student);


        spinner();
    }

    private void spinner() {
        //获取spinner控件
        Spinner spinner_demo = findViewById(R.id.spinner_demo);
        //1.创建数据源
        String[] startArray = {"水星","金星","地球"};
        //2.创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,startArray);
        //adapter.setDropDownViewResource(R.layout.item_dropdown);
        //3.将适配器设置给spinner
        spinner_demo.setAdapter(adapter);
        spinner_demo.setPrompt("请选择行星");
        spinner_demo.setSelection(0);
        //元素选中监听
        spinner_demo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getApplicationContext(), "你选择的是:"+startArray[position], Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


    public void listener() {

    }



    //下拉单选等组件
    public void checkBokSpinner(View view) {
        CheckBox checkBox = (CheckBox) view;
        boolean isChecked = checkBox.isChecked();
        if (isChecked){
            ll_spinner.setVisibility(View.VISIBLE);
        }else {
            ll_spinner.setVisibility(View.GONE);
        }
    }

    //弹框组件
    public void checkBokDialog(View view) {
        CheckBox checkBox = (CheckBox) view;
        boolean isChecked = checkBox.isChecked();
        if (isChecked){
            ll_dialog.setVisibility(View.VISIBLE);
        }else {
            ll_dialog.setVisibility(View.GONE);
        }
    }

    //文字效果
    public void checkBokText(View view) {
        CheckBox checkBox = (CheckBox) view;
        boolean isChecked = checkBox.isChecked();
        if (isChecked){
            ll_text.setVisibility(View.VISIBLE);
        }else {
            ll_text.setVisibility(View.GONE);
        }
    }

    //RecyclerView列表
    public void recyclerViewList(View view) {
        CheckBox checkBox = (CheckBox) view;
        boolean isChecked = checkBox.isChecked();
        if (isChecked){
            ll_RecyclerView.setVisibility(View.VISIBLE);
        }else {
            ll_RecyclerView.setVisibility(View.GONE);
        }
    }

    //扫描二维码案例
    public void scan(View view) {
        CheckBox checkBox = (CheckBox) view;
        boolean isChecked = checkBox.isChecked();
        if (isChecked){
            ll_scan.setVisibility(View.VISIBLE);
        }else {
            ll_scan.setVisibility(View.GONE);
        }
    }
    //****************************************************************************************//
    //文字跑马灯效果
    public void tvMarquee(View view) {
        tv_marquee.scrollTo(scrollX, 0);
        if (isPaused){
            scrollX = tv_marquee.getScrollX(); // 记录当前的滚动位置
            tv_marquee.setSelected(true);
            isPaused = false;
        }else {
            scrollX = tv_marquee.getScrollX(); // 记录当前的滚动位置
            tv_marquee.setSelected(false);
            isPaused = true;
        }
    }

    //原生日期封装
    public void dialogDateOld(View view) {
        //自定义组件
        View bottomView = LayoutInflater.from(GroupActivity.this).inflate(R.layout.bottom_dialog_date_time, null);
        //底部弹框
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
        ViewGroup parent = (ViewGroup) bottomView.getParent();
        if (parent != null) {
            parent.removeView(bottomView);
        }
        bottomSheetDialog.setContentView(bottomView);
        //设置弹框属性
        BottomSheetBehavior<View> behavior = BottomSheetBehavior.from((View) bottomView.getParent());
        behavior.setHideable(true);
        //behavior.setPeekHeight(700);//设置初始高度,根据需要设置这个值
        //behavior.setCanceledOnTouchOutside(false);//设置点击dialog外部不消失
        //显示弹框
        bottomSheetDialog.show();

        TextView tv_select_date = bottomView.findViewById(R.id.tv_select_date);
        DatePicker datePicker = bottomView.findViewById(R.id.datePicker);
        TimePicker timePicker = bottomView.findViewById(R.id.timePicker);
        System.out.println("当前日期："+datePicker.getDayOfMonth());
        System.out.println("当前日期："+datePicker.getMonth());
        System.out.println("当前日期："+datePicker.getYear());

        tv_select_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_date.setText(datePicker.getYear()+"-"+(datePicker.getMonth()+1)+"-"+datePicker.getDayOfMonth()+" "+timePicker.getHour()+":"+timePicker.getMinute());
                bottomSheetDialog.dismiss();
            }
        });


    }

    //日期插件1：卡片弹框
    //github原地址：https://github.com/loper7/DateTimePicker
    public void dialogDate1(View view) {
        //最简单的使用方式
        new CardDatePickerDialog.Builder(GroupActivity.this)
                .setTitle("选择时间日期")
                .setOnChoose("确定", aLong -> {
                    DateTime date = DateUtil.date(aLong.longValue());
                    String format = DateUtil.format(date, "yyyy-MM-d HH:mm:ss");
                    System.out.println(format);
                    tv_date.setText(format);
                    return null;
                }).build().show();
    }

    //日期插件2：卡片弹框,自定义属性
    public void dialogDate2(View view) {
        //自定义属性
        new CardDatePickerDialog.Builder(GroupActivity.this)
                .setTitle("选择时间日期")
                .showBackNow(false)//是否显示回到当前按钮
                .showFocusDateInfo(false)//是否显示选中日期信息
                .setThemeColor(getColor(R.color.orange))//设置主题颜色
                //.setAssistColor(getColor(R.color.gray))//设置辅助颜色
                //.setDividerColor(getColor(R.color.gray2))//设置分割线颜色
                .setChooseDateModel(0)
                .showDateLabel(true)//是否显示单位标签
                .setMinTime(Long.valueOf("1577808000000"))//设置最小时间
                .setWrapSelectorWheel(false)//设置是否循环滚动
                .setOnChoose("确定", aLong -> {
                    DateTime date = DateUtil.date(aLong.longValue());
                    String format = DateUtil.format(date, "yyyy-MM-d HH:mm:ss");
                    System.out.println(format);
                    tv_date.setText(format);
                    return null;
                }).build().show();
    }

    public void dialogDate3(View view) {

    }

    //封装警告弹框
    public void dialogAlert1(View view) {
        int screenHeight = SystemUtils.getScreenHeight(GroupActivity.this);
        int screenWidth = SystemUtils.getScreenWidth(GroupActivity.this);
        float screenDensity = SystemUtils.getScreenDensity(GroupActivity.this);
        SystemUtils.showAlertDialog(GroupActivity.this, "屏幕参数",
                "屏幕宽度：" + screenWidth + "px" +
                        "\n屏幕高度：" + screenHeight + "px" +
                        "\n屏幕像素密度：" + screenDensity);
    }

    //列表视图-RecyclerView
    public void loadRecyclerView(View view) {

        if (recyclerView_student.getVisibility() == View.GONE){
            recyclerView_student.setVisibility(View.VISIBLE);
            //请求后端数据
            testService.getList().enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        JSONObject data = RetrofitUtil.getDataFromResponse(response);
                        JSONArray rows = Data.getJSONArray(data, "data", new JSONArray());
                        ArrayList<Student> list = new ArrayList<>();
                        for (int i = 0; i < rows.size(); i++) {
                            Student student = new Student();
                            JSONObject json = rows.getJSONObject(i);
                            student.setStuNo(Data.getString(json,"userNo",""));
                            student.setStuName(Data.getString(json,"userName",""));
                            student.setSex(Data.getString(json,"sex",""));
                            list.add(student);
                        }

                        onloadRecyclerView(list);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable e) {
                    System.out.println(e.getMessage());
                }
            });
        }else {
            recyclerView_student.setVisibility(View.GONE);
        }

    }

    //渲染数据
    private void onloadRecyclerView(ArrayList<Student> list) {
        if (null == recyclerViewAdapter){
            recyclerViewAdapter = new RecyclerViewAdapter(list, GroupActivity.this);
            recyclerView_student.setLayoutManager(new LinearLayoutManager(GroupActivity.this));
            recyclerView_student.setAdapter(recyclerViewAdapter);
            int horizontalMargin = 16; // 假设左右边距为16dp
            int verticalMargin = 16;   // 假设上下外部边距为32dp
            recyclerView_student.addItemDecoration(new MyItemDecoration(horizontalMargin,verticalMargin));
        }else {
            recyclerViewAdapter.setData(list);
            recyclerViewAdapter.notifyDataSetChanged();
        }

    }

    //生成二维码
    public void createQrCode(View view) {
        String shareUrl = "https://www.baidu.com/";
        Bitmap bitmap  = ZXingUtils.createBitmap(shareUrl, 300, 300);
        Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_qr_logo);//logo添加
        Bitmap bitmap2 = ZXingUtils.addLogo(bitmap, bitmap1);
        if (bitmap2 == null) {
            return;
        }
        ImageView iv_qr = findViewById(R.id.iv_qr);
        iv_qr.setVisibility(View.VISIBLE);
        iv_qr.setImageBitmap(bitmap2);
    }

    //生成条形码
    public void createBarCode(View view) {
        String shareUrl = "123456780";
        Bitmap bitmap  = ZXingUtils.creatBarcode(this,shareUrl,
                600, 200,true);
        ImageView iv_bar = findViewById(R.id.iv_bar );
        iv_bar.setVisibility(View.VISIBLE);
        iv_bar.setImageBitmap(bitmap);

    }

    //开始扫描二维码/条形码
    public void scanner(View view) {
        //打开扫描界面扫描条形码或二维码  CaptureActivity可以使用框架的，也可以复制出来，自定义页面
        Intent openCameraIntent = new Intent(this, CaptureActivity.class);
        startActivityForResult(openCameraIntent, RESULT_SCAN);

    }

    //二维码扫描结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case RESULT_SPEECH: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> text = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    DialogUtils.show(GroupActivity.this,text.get(0));
                }
                break;
            }
            case RESULT_SCAN:{
                //处理扫描结果（在界面上显示）
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString("SCAN_RESULT");
                    Toast.makeText(this,"扫描结果："+scanResult,Toast.LENGTH_LONG).show();
                }
                break;
            }

        }

    }

    private TextToSpeech tts;//创建语音对象
    //语音广播
    public void voiceBroadcast(View view) {
        tts=new TextToSpeech(GroupActivity.this, new TextToSpeech.OnInitListener() {//实例化自带语音对象
            @Override
            public void onInit(int i) {
                if(i==TextToSpeech.SUCCESS){//设置语音
                    tts.setLanguage(Locale.CHINESE);//中文
                    tts.speak("今天温度36.3℃",TextToSpeech.QUEUE_FLUSH,null);//播报“今天温度36.3℃”
                }
            }
        });
    }


    public void voiceToText(View view) {
//        Intent intent = new Intent(
//                RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//        //语言模式和自由模式的语音识别    EXTRA_LANGUAGE_MODEL:语言模式  LANGUAGE_MODEL_FREE_FORM：自由模式语言
//        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//        //提示语音开始
//        intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"开始语音");
//        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
//
//        try {
//            startActivityForResult(intent, RESULT_SPEECH);
//
//        } catch (ActivityNotFoundException a) {
//            Toast t = Toast.makeText(getApplicationContext(),
//                    "Opps! Your device doesn't support Speech to Text",
//                    Toast.LENGTH_SHORT);
//            t.show();
//        }




        // 启动语音识别
        startSpeechRecognition();
    }

    private void startSpeechRecognition() {
        if (speechRecognizer == null) {
            Toast.makeText(this, "无法创建 SpeechRecognizer 实例", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-CN"); // 设置为中文
        speechRecognizer.startListening(intent); // 开始监听
    }


}